#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdbool.h>

#define SIZE_COMMAND 64
#define SIZE_COMLINE 1024

char* command[SIZE_COMMAND];
char com_line[SIZE_COMLINE];
char g_myenv[100];

//内置命令
bool inside_command()
{
    if(strcmp(command[0],"cd")==0)//cd命令
    {
        if(command[1] != NULL) chdir(command[1]);
        return true;
    }

    if(strcmp(command[0],"export")==0)
    {
        strcpy(g_myenv,command[1]);
        //printf("this is test:%s\n",g_myenv);
        //printf("this is test:%s\n",command[1]);
        if(putenv(g_myenv)==0)
          printf("%s: export success\n",g_myenv);
        //if(putenv(command[1])==0)
        //printf("%s: export success\n",command[1]);
        return true;
    }
   
    return false;
}



char *checkRedirect(int* num)
{
  char * tmp=com_line;
  char *end=tmp+strlen(com_line);
  while(end>=tmp)
  {
  if(*end=='>')//输出重定向echo aaaaa>tmp.txt
  {
    *end='\0';
    if(*(end-1)=='>')//追加重定向
    {
      *end='\0';
      *num=1;
      return end+1;
    }
    *num=0;//告诉main函数这是输出重定向
    return end+1;
  }
  if(*end=='<')//cat <tmp.txt
  {
    *end='\0';
    *num=2;
    return end+1;
  }
  end--;
  }
  return NULL;
   
}


//获得命令
bool get_command()
{
      printf("[this is myshell]$ ");      
      //把储存我们的命令字符串的字符初始化为全0      
      memset(com_line,0,SIZE_COMLINE);      
      if(NULL==fgets(com_line,sizeof(com_line),stdin))
      {
        printf("get_command fail\n");
        exit(0);
      }
      //处理特殊情况因为我们的回车\n也被fgets读入了      
      com_line[strlen(com_line)-1]='\0';      
      //开始分割字符串到数组command中      
      memset(command,0,SIZE_COMMAND);
      command[0]=strtok(com_line," ");      
      int index=0;
      //增加配色方案
      if(strcmp(command[0],"ls")==0)
      {
        command[++index]=(char*)"--color=auto";
      }
      //继续分割字符串
      while(command[index]!=NULL)      
      {      
          command[++index]=strtok(NULL," ");
      }    
      //测试一一下是否分隔成功    
      //int i=0;    
      //while(command[i]!=NULL)    
      //{    
      //    printf("%s\n",command[i++]);    
      //}
      
      //如果执行了内置命令就会返回false
      if(inside_command())
        return false;
      //正常要子进程执行命令则返回true
      return true;
}

int main()
{
    extern char **environ;
    while(1)
    {
        if(get_command()==false)
          continue;
        pid_t pid=fork();
        if(pid==0)
        {

          //子进程执行
          //execvp(command[0],command;//方法1
          execvpe(command[0],command,environ);
        }
        else if(pid<0)
        {
          printf("命令执行失败\n");
        }
        wait(NULL);
    }
    return 0;
}

